package com.langshixiaobai.mqdemo.server.datacenter;

import com.langshixiaobai.mqdemo.common.MqException;
import com.langshixiaobai.mqdemo.server.core.Binding;
import com.langshixiaobai.mqdemo.server.core.Exchange;
import com.langshixiaobai.mqdemo.server.core.MSGQueue;
import com.langshixiaobai.mqdemo.server.core.Message;

import java.io.IOException;
import java.util.List;
import java.util.Queue;

//将内部操作封装，对用户提供相应功能的接口，用户只需要调用即可，不需要知道内部如何实现
public class DiskDataCenter {

    private DataBaseManager dataBaseManager = new DataBaseManager();

    private MessageFileManager messageFileManager = new MessageFileManager();

    //进行初始化
    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    //封装插入交换机接口api
    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }

    //封装删除交换机接口
    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }

    //查找所有交换机
    public List<Exchange> selectAllExchanges() {
        return dataBaseManager.findAllExchange();
    }

    public void insertQueue(MSGQueue queue) {
        dataBaseManager.insertQueue(queue);
    }


    public List<MSGQueue> selectAllQueues() {
        return dataBaseManager.findAllQueue();
    }

    public void deleteQueue(String queueName) {
        dataBaseManager.deleteQueue(queueName);
    }

    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }

    public List<Binding> selectBinding() {
        return dataBaseManager.findAllBinding();
    }

    public void sendMessage(MSGQueue queue, Message message) throws MqException {
        messageFileManager.sendMessage(queue, message);
    }

    //删除消息
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, MqException {
        //删除消息
        messageFileManager.deleteMessageFile(queue, message);
        //检测是否出发GC
        if(messageFileManager.checkGC(queue.getName())){
            //GC回收
            messageFileManager.gc(queue);
        }
    }
}
